# -*- coding: utf-8 -*-
"""
Created on Mon Aug 13 11:09:57 2018

@author: jiujiujiu
"""

from WriteData import writedata
from Tk import genearteMD5
import requests
import re
import time


def postHTMLText(url, data):
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'}
    try:
        r = requests.post(url, data=data, headers=header)
        #        html = r.text
        html = r.text
        #        print(html)
        return html

    except:
        return None


def get_data(url, data):
    html = postHTMLText(url, data)
    if not html:
        return None
    rr = re.compile(r'<span class="item-meta-li date">([\s\S]*?)</span>')
    datas = re.findall(rr, html)
    return datas


def count_process_one():
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    h = time.strftime("%H", time.localtime())
    while a < 200:
        url = 'http://www.kejigezi.com/wp-admin/admin-ajax.php'
        data = {
            'action': 'wpcom_load_posts',
            'page': a
        }
        a += 1
        datas = get_data(url, data)
        if not datas:
            continue
        for date in datas:
            date = date.strip()
            if '分钟前' in date:
                d1 += 1
            elif ('小时前' in date) and (int(date[:-3]) - int(h)) <= 0:
                d1 += 1
            elif ('小时前' in date) and (int(date[:-3]) - int(h)) > 0:
                d2 += 1
            elif '1天前' in date:
                d2 += 1
            elif '2天前' in date:
                d3 += 1
            else:
                d4 += 1
        if d4 != 0:
            break
    return (d1, d2, d3)


def main():
    u = '一号财经'
    t1 = count_process_one()
    print(t1)
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0], "yesterday": t1[1], "frontday": t1[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
